package com.ccl.iot.ir;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.ccl.iot.IOTNetAPIConst;
import com.ccl.iot.bean.CodeviewBean;
import com.ccl.iot.device.IOTBLDNADevice;
import com.ccl.iot.device.IOTBLir;
import com.ccl.iot.managers.DeviceManager;
import com.ccl.iot.managers.UserManager;
import com.mysql.jdbc.Connection;

import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;

import cn.com.broadlink.sdk.BLLet;
import cn.com.broadlink.sdk.constants.controller.BLControllerErrCode;
import cn.com.broadlink.sdk.param.controller.BLConfigParam;
import cn.com.broadlink.sdk.result.controller.BLDownloadScriptResult;

/**
 * 创建者     王浩
 * 创建时间   2017/5/19 10:29
 * 描述	      ${TODO}
 */

public class BroadLinkManager {

    private static BroadLinkManager mInstance;
    private final UserManager mUserManager;
    private final DeviceManager mDeviceManager;
    private ArrayList<IOTBLDNADevice> mAllIRDevice;
    private ArrayList<IOTBLir> mAllIOTDevs;

    public static BroadLinkManager Init(Context context) {
        if (mInstance == null) {
            mInstance = new BroadLinkManager(context);
        }
        return mInstance;
    }

    public static BroadLinkManager GetDefaultManager() {
        return mInstance;
    }

    private Context mContext;

    private BroadLinkManager(Context context) {
        mContext = context;
        //初始化博联SDK
        BLConfigParam config = new BLConfigParam();
        config.put(BLConfigParam.HTTP_TIMEOUT, "10000");
        BLLet.init(mContext, config);
        BLLet.DebugLog.on();
        mUserManager = UserManager.GetDefaultManager();
        mDeviceManager = DeviceManager.GetDefaultManager();
        mAllIOTDevs = new ArrayList<>();
    }

    public void startScan() {
        synchronized (BroadLinkManager.class) {
            long logonUser = mUserManager.getLogonUser();
            if (logonUser != IOTNetAPIConst.KINVALID_ID) {
                Connection dbConn = DBUtils.getDBConn();
                if (dbConn != null) {
                    //获取到当前用户id下的所有红外设备
                    mAllIRDevice = DBUtils.getAllIRDevice(logonUser, dbConn);

                    if (mAllIRDevice != null && mAllIRDevice.size() > 0) {
                        for (IOTBLDNADevice blDev : mAllIRDevice) {
                            if (blDev != null) {
                                buildIrDev(dbConn, blDev);
                            }
                        }
                    }
                    try {
                        dbConn.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 将博联的红外设备构建成IOT设备,并获取传入设备的所有红外码
     *
     * @param dbConn
     * @param blDev
     */
    private void buildIrDev(Connection dbConn, IOTBLDNADevice blDev) {
        long dbId = blDev.getDbId();
        //转换成当前app架构下的id
        long id = dbId | 0x800000000000L;
        if (mAllIOTDevs.size() > 0) {
            for (IOTBLir dev : mAllIOTDevs) {
                if (dev != null) {
                    if (dev.getID() == id) {
                        dev.clearSubDev();
                        ArrayList<CodeviewBean> allCodeview = DBUtils.getAllCodeview(dbId, dbConn);
                        if (allCodeview != null && allCodeview.size() > 0) {
                            for (CodeviewBean bean : allCodeview) {
                                if (bean != null) {
                                    dev.addIrCode(bean);
                                }
                            }
                        }
                        return;
                    }
                }
            }
        }
        IOTBLir iotDevice = new IOTBLir(id, dbId, blDev);
        if (iotDevice != null) {
            mAllIOTDevs.add(iotDevice);
            //检查脚本
            scriptFileExist(blDev.getPid());
            mDeviceManager.setOnline(iotDevice, true);
            BLLet.Controller.addDevice(blDev);
            //获取红外设备所有红外码
            ArrayList<CodeviewBean> allCodeview = DBUtils.getAllCodeview(dbId, dbConn);
            for (CodeviewBean bean : allCodeview) {
                if (bean != null) {
                    iotDevice.addIrCode(bean);
                }
            }
            mDeviceManager.addDevice(iotDevice, id);
        }
    }


    public ArrayList<IOTBLir> getAllBlirDevs() {
        return mAllIOTDevs;
    }


    /**
     * 检查设备对应的脚本是否存在, 如不存在则下载
     *
     * @param pid
     */
    private void scriptFileExist(String pid) {
        if (pid != null) {
            /***获取产品脚本本地保存的路径***/
            String scriptFilePath = BLLet.Controller.queryScriptPath(pid);
            Log.e("FileExist", scriptFilePath);
            File file = new File(scriptFilePath);
            if (!file.exists()) {
                new DownLoadScriptTask().execute(pid);
            }
        }
    }

    //脚本下载
    class DownLoadScriptTask extends AsyncTask<String, Void, BLDownloadScriptResult> {

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected BLDownloadScriptResult doInBackground(String... params) {
            return BLLet.Controller.downloadScript(params[0]);
        }

        @Override
        protected void onPostExecute(BLDownloadScriptResult result) {
            super.onPostExecute(result);
            if (result != null && result.getStatus() == BLControllerErrCode.SUCCESS) {
                //                Messager.Show("Script Path ：" + result.getSavePath());
            }
        }
    }


}
